//
//  LTDetailViewController.m
//  LocalTravel
//
//  Created by zheng ji on 14-3-16.
//  Copyright (c) 2014年 jxw. All rights reserved.
//

#import "LTDetailViewController.h"

@interface LTDetailViewController ()
{
    NSString* _sceneryIntro;//景点简介
    NSString* _buyNotice;//购票须知
    NSString* _traffic;//交通
    NSString* _address;
    NSMutableString* _cssData;
    UIWebView* _webView;
    UISegmentedControl* _segControl;
     NSString* _sceneryId;
    
    UIActivityIndicatorView *_activityView;
    UILabel* _loadMoreTip;
    BOOL _needScale;
}
@end

@implementation LTDetailViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    _needScale=YES;
      _sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
    //_address=@"";
	_cssData=[[NSMutableString alloc]init];
    
    [_cssData appendString:@"<link rel='stylesheet' type='text/css' href='http://css.40017.cn/cn/min/??/cn/c/c/2013/base_1_9.css,/cn/c/c/common-aspect.0.0.1.css?v=2014022401' media='screen'/>"];
    [_cssData appendString:@"<link rel='stylesheet' type='text/css' href='http://css.40017.cn/cn/min/??/cn/c/s/2013/search.0.0.1.css,/cn/s/c/2013/sCommon.0.0.4.css,/cn/s/api/2014/scenery_api.0.1.4.css,/cn/s/final/2014/sFinal.0.6.7.css?v=201401270004' media='screen' />"];
    [_cssData appendString:@"<link rel='stylesheet' type='text/css' href='http://css.40017.cn/cn/s/map/2013/sFinal_map.0.0.1.css?v=1230300WW' media='screen'/>"];

    
    _webView=[[UIWebView alloc]initWithFrame:CGRectMake(self.view.frame.origin.x, self.view.frame.origin.y, 850, 620)];
    _webView.delegate=self;
    
    _webView.backgroundColor=[UIColor clearColor];
    
    [self.view addSubview:_webView];
    
    [self createActivityIndicatorView];
    
    
    [self createTitleBar];
    
    [self showTitle];
    
}
-(void)createActivityIndicatorView{
    _activityView=[[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    
    CGRect activityFrame=_activityView.frame;
    activityFrame.origin.x=_webView.frame.size.width/2-50;
    activityFrame.origin.y=_webView.frame.size.height/2;
    
    [_activityView setFrame:activityFrame];
    
    _activityView.activityIndicatorViewStyle=UIActivityIndicatorViewStyleGray;
    
    
    
    _loadMoreTip=[[UILabel alloc] initWithFrame:CGRectMake(activityFrame.origin.x+30, activityFrame.origin.y+5, 100, 20)];
    
    _loadMoreTip.textAlignment=NSTextAlignmentCenter;
    
    _loadMoreTip.text=@"正在加载数据";
    _loadMoreTip.textColor=[UIColor redColor];
    _loadMoreTip.font=[UIFont systemFontOfSize:16];
    _loadMoreTip.backgroundColor=[UIColor clearColor];
    
    [_webView addSubview:_activityView];
    [_webView addSubview:_loadMoreTip];
    [_activityView startAnimating];
    _activityView.hidden=NO;
    _loadMoreTip.hidden=NO;
}
- (void)webViewDidStartLoad:(UIWebView *)webView{
    [_activityView startAnimating];
    _activityView.hidden=NO;
    _loadMoreTip.hidden=NO;
}
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    [_activityView stopAnimating];
    _activityView.hidden=YES;
    _loadMoreTip.hidden=YES;
    
    if(_needScale){
        CGSize contentSize = webView.scrollView.contentSize;
        CGSize viewSize = self.view.bounds.size;
        
        float scale = viewSize.width / contentSize.width;
        if (scale < 0.9) {
            NSLog(@"Zoom out fix for web view: %f", scale);
            
            _webView.scrollView.minimumZoomScale = scale;
            _webView.scrollView.maximumZoomScale = scale+5;
            _webView.scrollView.zoomScale = scale;
        }

    }
}
-(void)viewDidAppear:(BOOL)animated{
    [self show:0];
}
-(void)showTitle{
    if(self.dictScenery==nil) return ;
    
    NSString* sceneryName=[self.dictScenery objectForKey:@"sceneryName"];
    NSString* cityName=[self.dictScenery objectForKey:@"cityName"];
    self.navigationItem.title=[NSString stringWithFormat:@"%@[%@]",sceneryName,cityName];
    
    
}
-(void)showInWebViewNoCss:(NSString*)htmlData{
    NSMutableString* str=[[NSMutableString alloc]init];
    if(htmlData==nil || [htmlData isEqualToString:@""]){
        [str appendString:@"<h5>暂无信息。</h5>"];
    }
    [str appendString:htmlData];
    NSData* data=[ str dataUsingEncoding:NSUTF8StringEncoding];
    [_webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil];

}
-(void)showInWebView:(NSString*)htmlData{
    NSMutableString* str=[[NSMutableString alloc]init];
    
    if(htmlData==nil || [htmlData isEqualToString:@""]){
        [str appendString:@"<h5>暂无信息。</h5>"];
    }else{
    
     [str appendString:_cssData];
    [str appendString:htmlData];
    }
    NSData* data=[ str dataUsingEncoding:NSUTF8StringEncoding];
    //_webView.clearsContextBeforeDrawing;
    [_webView loadData:data MIMEType:@"text/html" textEncodingName:@"UTF-8" baseURL:nil];
 
}
-(void)show:(NSInteger)index{
    _needScale=NO;
    if(index==0){
        //显示简介
        if(_sceneryIntro==nil){
            [self loadSceneryDetail];
        }
        [self showInWebView:_sceneryIntro];
        _needScale=YES;
    }else if(index==1){
        //显示购票须知
        if(_buyNotice==nil){
            [self loadSceneryDetail];
        }
        [self showInWebViewNoCss:_buyNotice];
    }else if(index==2){
        //显示交通
        if(_traffic==nil){
            [self loadSceneryTraffic];
        }
        if(_address !=nil){
            [self showInWebViewNoCss:[NSString stringWithFormat:@"地址：<h4>%@</h4><br/>%@",_address,_traffic]];
        }else{
           [self showInWebViewNoCss:_traffic];
        }
    }else if(index==3){
        //景点图片
        [self showImagePreview];
    }else if(index==4){
        //景点图片
        [self showTicketController];
    }
 
}
-(void)showTicketController{
   
    LTTicketController* ticketController=[[LTTicketController alloc]init];
    ticketController.dictScenery=self.dictScenery;
    UINavigationController* navi=[[UINavigationController alloc] initWithRootViewController:ticketController];
    navi.navigationBar.translucent=NO;
    
    /*
    UIPopoverController* popover=[[UIPopoverController alloc]initWithContentViewController:navi];
    
    popover.popoverContentSize=CGSizeMake(800, 700);
    [popover presentPopoverFromRect:_segControl.frame inView:self.view permittedArrowDirections:UIPopoverArrowDirectionAny animated:YES];
    */
    
    navi.modalPresentationStyle=UIModalPresentationFormSheet;
    navi.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
    
    [self presentViewController:navi animated:YES completion:nil];
    
    
    ticketController=nil;
     
    
    _segControl.selectedSegmentIndex=-1;
}
-(void)showImagePreview{
    LTImagePreviewViewController* imageController=[[LTImagePreviewViewController alloc]init];
    imageController.dictScenery=self.dictScenery;
    UINavigationController* navi=[[UINavigationController alloc] initWithRootViewController:imageController];
    navi.navigationBar.translucent=NO;
    navi.modalPresentationStyle=UIModalPresentationFormSheet;
    navi.modalTransitionStyle=UIModalTransitionStyleCoverVertical;
    
    [self presentViewController:navi animated:YES completion:nil];
    //[self presentViewController:navi animated:YES completion:nil];
     imageController=nil;
    _segControl.selectedSegmentIndex=-1;
    
    
}
-(void)viewDidDisappear:(BOOL)animated{
    
    _webView.delegate=nil;
    _webView=nil;
    _segControl=nil;
}
-(void)segmentControlChange:(UISegmentedControl*)segControl{
    [self show:segControl.selectedSegmentIndex];
}

-(void)readSceneryTrafficFromNet{
     NSString* sceneryId=[self.dictScenery objectForKey:@"sceneryId"];
     NSString* xmlData=   [LocalTravelRequest getSceneryTrafficInfo:sceneryId];
    SceneryTrafficParse* parse=[[SceneryTrafficParse alloc]initWithXmlData:xmlData];
    
    NSDictionary* dict=[parse getScenaryTraffic];
    [self parseSceneryTraffic:dict];
    parse=nil;
    
    [NSThread detachNewThreadSelector:@selector(writeSceneryTrafficToLocal:) toTarget:self withObject:dict];
    
}
-(void)writeSceneryTrafficToLocal:(NSDictionary*)dict{
    if(dict==nil || dict.count==0)return ;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@_traffic.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    [CommonConfigUtil writeJsonToLocal:dict localFile:localCityJson];
    
}
-(void)readSceneryTrafficFromLocal{
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_traffic.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    NSData* jsonData=[NSData dataWithContentsOfFile:localJson];
    if(jsonData !=nil){
        NSError* error;
        NSDictionary* dictImage=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || dictImage==nil ) {
            [self readSceneryTrafficFromNet];//从网络获取
        }else{
            [self parseSceneryTraffic:dictImage];
            
        }
    }
    
}
-(void)parseSceneryTraffic:(NSDictionary*)dict{
    
    if(dict !=nil){
        _traffic=[dict objectForKey:@"traffic"];
        if(_traffic==nil)_traffic=@"";
    }
    
    dict=nil;
}
-(void)loadSceneryTraffic{
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_traffic.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    if([CommonConfigUtil existFileWithLocalPath:localJson]){
        //从本地读取
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localJson error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladDataTimeSecond]){
                
                //从网络获取
                [self readSceneryTrafficFromNet];
                
            }else{
                //从本地获取
                [self readSceneryTrafficFromLocal];
            }
        }else{
            //从网络获取
            [self readSceneryTrafficFromNet];
        }
        
        
    }else{
        //从网络读取
        [self readSceneryTrafficFromNet];
    }
    

}
-(void)loadSceneryDetail{
    
  
    
NSString* localJson=[NSString stringWithFormat:@"%@/%@_detail.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    if([CommonConfigUtil existFileWithLocalPath:localJson]){
        //从本地读取
        NSDictionary *fileAttributes=[[NSFileManager defaultManager] attributesOfItemAtPath:localJson error:nil];
        if(nil!=fileAttributes){
            NSDate *fileModifyDate=  [fileAttributes objectForKey:NSFileModificationDate];
            NSTimeInterval timesecod= [[NSDate date] timeIntervalSinceDate:fileModifyDate];
            // NSLog(@"timesecod:%f",timesecod);
            if(nil!=fileModifyDate && timesecod>[CommonConfigUtil getRoladDataTimeSecond]){
                
                //从网络获取
                [self readSceneryDetailFromNet];
                
            }else{
                //从本地获取
                [self readSceneryDetailFromLocal];
            }
        }else{
            //从网络获取
            [self readSceneryDetailFromNet];
        }
        

    }else{
        //从网络读取
        [self readSceneryDetailFromNet];
    }
   
    
}
-(void)readSceneryDetailFromLocal{
    NSString* localJson=[NSString stringWithFormat:@"%@/%@_detail.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    NSData* jsonData=[NSData dataWithContentsOfFile:localJson];
    if(jsonData !=nil){
        NSError* error;
        NSDictionary* dictImage=  [NSJSONSerialization JSONObjectWithData:jsonData options:kNilOptions error:&error];
        if (error || dictImage==nil ) {
            [self readSceneryDetailFromNet];//从网络获取
        }else{
            [self parseSceneryDetail:dictImage];
            
        }
    }

}
-(void)readSceneryDetailFromNet{
    NSString* xmlData=   [LocalTravelRequest getSceneryDetail:_sceneryId cc:@"2"];
    
    SceneryDetailParse* parse=[[SceneryDetailParse alloc]initWithXmlData:xmlData];
    
    NSDictionary* dict=[parse getScenaryDetail];
    [self parseSceneryDetail:dict];
        parse=nil;
      [NSThread detachNewThreadSelector:@selector(writeSceneryDetailToLocal:) toTarget:self withObject:dict];
}
-(void)writeSceneryDetailToLocal:(NSDictionary*)dict{
    if(dict==nil || dict.count==0)return ;
    NSString* localCityJson=[NSString stringWithFormat:@"%@/%@_detail.json",[CommonConfigUtil getFileLocalPath],_sceneryId ];
    
    [CommonConfigUtil writeJsonToLocal:dict localFile:localCityJson];
    
}
-(void)parseSceneryDetail:(NSDictionary*)dict{
    if(dict !=nil){
        _sceneryIntro=[dict objectForKey:@"intro"];
        _buyNotice=[dict objectForKey:@"buyNotice"];
        _address=[dict objectForKey:@"address"];
    }
    
    dict=nil;

}
-(void)createTitleBar{
    //NSArray* segItems=[NSArray arrayWithObjects:@"",@"", nil];
    
       _segControl=[[UISegmentedControl alloc]initWithItems:[NSArray arrayWithObjects:@"景点简介",@"购票须知",@"交通",@"景点图片",@"门票",nil]];
    [_segControl addTarget:self action:@selector(segmentControlChange:) forControlEvents:UIControlEventValueChanged];
    UIBarButtonItem* item=[[UIBarButtonItem alloc]initWithCustomView:_segControl];
    // searchBar.delegate = self;
    self.navigationItem.leftBarButtonItem=item;
    //_segControl=nil;
    item=nil;

    
}
//-(void)webViewDidFinishLoad:(UIWebView *)webView{
  /*
     CGSize contentSize = webView.scrollView.contentSize;
     CGSize viewSize = self.view.bounds.size;
     
     float scale = viewSize.width / contentSize.width;
     if (scale < 0.9) {
     NSLog(@"Zoom out fix for web view: %f", scale);
     
     _webView.scrollView.minimumZoomScale = scale;
     _webView.scrollView.maximumZoomScale = scale+5;
     _webView.scrollView.zoomScale = scale;
     }
   */ 
    
//}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
